package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.ShoppingCartItem;

public class DeleteItemFromShoppingCartServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public DeleteItemFromShoppingCartServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		HttpSession session = request.getSession();
		ArrayList<ShoppingCartItem> cart = (ArrayList<ShoppingCartItem>) session.getAttribute("cart");
		//Integer nbrOfItems = (Integer) session.getAttribute("nbrOfItems");
		String itemNumber = request.getParameter("itemId");
		for (ShoppingCartItem i : cart) {
			if (i.getItemNumber() == Integer.parseInt(itemNumber)) {
				cart.remove(i);
				break;
			}
		}
		double totalPrice = 0;
		for (ShoppingCartItem i : cart) {
			totalPrice += Integer.parseInt(i.getQuantity()) * i.getPrice();
		}
		session.setAttribute("total", totalPrice);
		session.setAttribute("cart", cart);
		
		//Check how many items are there in the cart
		int nbrOfItems = 0;
		for (ShoppingCartItem i : cart) {
			nbrOfItems += Integer.parseInt(i.getQuantity());
		}
		
		session.setAttribute("nbrOfItems", nbrOfItems);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
